package cn.mymall.service.mall.impl;

import cn.mymall.constant.MallConstant;
import cn.mymall.entity.mall.Sku;
import cn.mymall.mapper.SkuMapper;
import cn.mymall.service.impl.BaseServiceImpl;
import cn.mymall.service.mall.ISkuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SkuServiceImpl extends BaseServiceImpl<SkuMapper, Sku> implements ISkuService {

	@Override
	public List<Sku> findByProductId(Integer productId) {
		QueryWrapper<Sku> ew = new QueryWrapper<Sku>();
		ew.eq("product_id", productId);
		ew.orderByAsc("id");
		List<Sku> skuList = list(ew);
		return skuList;
	}

	@Override
	public List<Sku> findBookingByProductId(Integer productId) {
		List<Sku> skuList = findByProductId(productId).stream().filter(sku -> sku.hasBooking()).collect(Collectors.toList());
		return skuList;
	}

	@Override
	public Sku findByProductIdById(Integer productId) {
		List<Sku> list = list(new QueryWrapper<Sku>().eq("product_id", productId));
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		return list.get(0);
	}

	@Override
	public Integer findProductStockCountByProductId(Integer productId) {
		String sql = "select sum(init_stock) from sku where product_id=? and status=?";
		Integer res = jdbcTemplate.queryForObject(sql, Integer.class, productId, MallConstant.SKU_STATUS_ON_SALE);
		if(res==null){
			res = 0;
		}
		return res ;
	}

}
